/*
 * support3
 */
package com.pitop.errorcode.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baidu.fsg.uid.UidGenerator;
import com.pitop.core.base.BaseDAO;
import com.pitop.core.base.BaseSVImpl;
import com.pitop.core.entity.Page;
import com.pitop.core.exceptions.BaseException;
import com.pitop.core.exceptions.ErrorcodeLocalException;
import com.pitop.core.exceptions.FrontendI18nException;
import com.pitop.core.tools.StringTools;
import com.pitop.errorcode.dao.ErrorcodeLocalDAO;
import com.pitop.errorcode.dao.ErrorcodePoolDAO;
import com.pitop.errorcode.entity.ErrorcodeLocal;
import com.pitop.errorcode.entity.ErrorcodeLocalState;
import com.pitop.errorcode.entity.ErrorcodePool;
import com.pitop.errorcode.vo.ErrorcodeLocalVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.HashedMap;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("errorcodeLocalSV")
//@CacheConfig(cacheNames = "Support:ErrorcodeLocal_Cache")
@Slf4j
public class ErrorcodeLocalSVImpl extends BaseSVImpl<ErrorcodeLocal, Long> implements ErrorcodeLocalSV {

    @Autowired
    private ErrorcodeLocalDAO errorcodeLocalDAO;

    @Autowired
    private ErrorcodePoolDAO errorcodePoolDAO;

    @Resource
    private UidGenerator uidGenerator;

    @Override
    protected BaseDAO getBaseDAO() {
        return errorcodeLocalDAO;
    }

    /**
     * 保存ErrorcodeLocal对象
     *
     * @param entity 实体
     * @throws BaseException
     */
    @Override
    //@CacheEvict(allEntries = true)
    public void save(ErrorcodeLocal entity) throws BaseException {
        //1.数据合法性验证：非空验证
        if (entity == null) {
            throw new ErrorcodeLocalException(BaseException.BaseExceptionEnum.Empty_Param);
        }
        //分类编码是否正确
        ErrorcodePool errorcodePool = errorcodePoolDAO.loadByErrorCode(entity.getErrorCode());
        if (errorcodePool == null) {
            throw new ErrorcodeLocalException(BaseException.BaseExceptionEnum.Result_Not_Exist);
        }
        //查询插入或修改的数据是否为空
        List<ErrorcodeLocalVO> errorcodeLocalVOList = entity.getErrorcodeLocalVOS();
        if (errorcodeLocalVOList == null || errorcodeLocalVOList.size() < 0) {
            throw new FrontendI18nException(BaseException.BaseExceptionEnum.Empty_Param);
        }
        //2.遍历插入或修改数据
        ErrorcodeLocal errorcodeLocal;
        Map<String, Object> params;
        for (ErrorcodeLocalVO errorcodeLocalVO : errorcodeLocalVOList) {
            if (StringTools.isNotEmpty(errorcodeLocalVO.getInfo())) {
                params = new HashedMap();
                params.put("errorCode", entity.getErrorCode());
                params.put("language", errorcodeLocalVO.getLanguage());
                errorcodeLocal = this.load(params);
                if (errorcodeLocal == null) {
                    //保存数据
                    entity.setCode(String.valueOf(uidGenerator.getUID()));
                    entity.setErrorCode(entity.getErrorCode());
                    entity.setSceneCode(entity.getSceneCode());
                    entity.setLanguage(errorcodeLocalVO.getLanguage());
                    entity.setInfo(errorcodeLocalVO.getInfo());
                    super.save(entity);
                } else {
                    //修改数据
                    entity.setErrorCode(entity.getErrorCode());
                    entity.setSceneCode(entity.getSceneCode());
                    errorcodeLocal.setInfo(errorcodeLocalVO.getInfo());
                    this.update(errorcodeLocal);
                }
            }
        }
    }

    /**
     * 数据更新
     *
     * @param errorcodeLocal 错误码实体
     */
    @Override
//    @CacheEvict(allEntries = true)
    public void modify(ErrorcodeLocal errorcodeLocal) {
        getBaseDAO().update(errorcodeLocal);
    }


    /**
     * 加载一个对象ErrorcodeLocal
     *
     * @param id
     * @param code 编码
     * @return ErrorcodeLocal
     */
    @Override
//    @Cacheable(key = "T(String).valueOf(#id).concat('-').concat(#code)")
    public ErrorcodeLocal load(Long id, String code) {
        if (id == null && code == null) {
            throw new ErrorcodeLocalException(BaseException.BaseExceptionEnum.Illegal_Param);
        }

        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return errorcodeLocalDAO.load(param);
    }

    /**
     * 加载一个对象ErrorcodeLocal 通过id
     *
     * @param id
     * @return ErrorcodeLocal
     */
    @Override
//    @Cacheable(key = "T(String).valueOf(#id)")
    public ErrorcodeLocal loadById(Long id) {
        if (id == null) {
            throw new ErrorcodeLocalException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return errorcodeLocalDAO.loadById(id);
    }

    /**
     * 加载一个对象ErrorcodeLocal 通过code
     *
     * @param code 编码
     * @return ErrorcodeLocal
     */
    @Override
//    @Cacheable(key = "#p0")
    public ErrorcodeLocal loadByCode(String code) {
        if (code == null) {
            throw new ErrorcodeLocalException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        return errorcodeLocalDAO.loadByCode(code);
    }

    /**
     * 根据场景编码、错误编码、语言查询错误信息数据
     *
     * @param errorcodeLocal
     * @return
     */
//    @Cacheable(key = "#errorcodeLocal.errorCode.concat('-').concat(#errorcodeLocal.language)")
    public ErrorcodeLocal loadByScodeAndEcodeAndLanguage(ErrorcodeLocal errorcodeLocal) {
        return errorcodeLocalDAO.loadByScodeAndEcodeAndLanguage(errorcodeLocal);
    }

    /**
     * 根据主键id,oldStates 共同更新 ErrorcodeLocal 的状态到newState状态
     *
     * @param id
     * @param newState  新状态
     * @param oldStates 旧状态集合
     */
    @Override
//    @CacheEvict(allEntries = true)
    public void updateStateById(Long id, ErrorcodeLocalState newState, ErrorcodeLocalState... oldStates) {
        if (id == null) {
            throw new ErrorcodeLocalException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (newState == null) {
            throw new ErrorcodeLocalException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (oldStates == null) {
            throw new ErrorcodeLocalException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        String[] states = new String[oldStates.length];
        for (int i = 0; i < oldStates.length; i++) {
            states[i] = oldStates[i].name();
        }
        errorcodeLocalDAO.updateStateById(id, new Date(), newState.name(), states);
    }

    /**
     * 根据主键code,oldStates 共同更新 ErrorcodeLocal 的状态到newState状态
     *
     * @param code      编码
     * @param newState  新状态
     * @param oldStates 旧状态集合
     */
    @Override
//    @CacheEvict(allEntries = true)
    public void updateStateByCode(String code, ErrorcodeLocalState newState, ErrorcodeLocalState... oldStates) {
        if (code == null) {
            throw new ErrorcodeLocalException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (newState == null) {
            throw new ErrorcodeLocalException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        if (oldStates == null) {
            throw new ErrorcodeLocalException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        String[] states = new String[oldStates.length];
        for (int i = 0; i < oldStates.length; i++) {
            states[i] = oldStates[i].name();
        }
        errorcodeLocalDAO.updateStateByCode(code, new Date(), newState.name(), states);
    }

    /**
     * 根据主键id 更新 ErrorcodeLocal 的状态到另一个状态
     *
     * @param id
     * @param state 状态
     */
    @Override
//    @CacheEvict(allEntries = true)
    public void updateById(Long id, ErrorcodeLocalState state) {
        if (id == null) {
            throw new ErrorcodeLocalException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        errorcodeLocalDAO.updateById(id, state.name(), new Date());
    }

    /**
     * 根据主键code 更新 ErrorcodeLocal 的状态到另一个状态
     *
     * @param code  编码
     * @param state 状态
     */
    @Override
//    @CacheEvict(allEntries = true)
    public void updateByCode(String code, ErrorcodeLocalState state) {
        if (code == null) {
            throw new ErrorcodeLocalException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        errorcodeLocalDAO.updateByCode(code, state.name(), new Date());
    }


    /**
     * 删除对象ErrorcodeLocal
     *
     * @param id * @param code 编码
     * @return ErrorcodeLocal
     */
    @Override
//    @CacheEvict(allEntries = true)
    public void delete(Long id, String code) {
        if (id == null && code == null) {
            throw new ErrorcodeLocalException(BaseException.BaseExceptionEnum.Illegal_Param);
        }
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        errorcodeLocalDAO.delete(param);
    }


    /**
     * 查询ErrorcodeLocal分页
     *
     * @param errorcodeLocal 对象
     * @param offset         查询开始行
     * @param limit          查询行数
     * @return List<ErrorcodeLocal>
     */
    @Override
//    @Cacheable(key = "'list'")
    public List<ErrorcodeLocal> list(ErrorcodeLocal errorcodeLocal, int offset, int limit) {
        if (offset < 0) {
            offset = 0;
        }

        if (limit < 0) {
            limit = Page.limit;
        }

        Map<String, Object> map = null;
        if (errorcodeLocal != null) {
            map = JSON.parseObject(JSON.toJSONString(errorcodeLocal, SerializerFeature.WriteDateUseDateFormat));
        } else {
            map = new HashMap<>();
        }
        return errorcodeLocalDAO.list(map, new RowBounds(offset, limit));
    }

    @Override
    public int count(ErrorcodeLocal errorcodeLocal) {
        Map<String, Object> map = null;
        if (errorcodeLocal != null) {
            map = JSON.parseObject(JSON.toJSONString(errorcodeLocal, SerializerFeature.WriteDateUseDateFormat));
        } else {
            map = new HashMap<>();
        }
        return errorcodeLocalDAO.count(map);
    }

    /**
     * 查询ErrorcodeLocal分页
     *
     * @param id     * @param code  编码
     * @param offset 查询开始行
     * @param limit  查询行数
     * @return List<ErrorcodeLocal>
     */
    @Override
//    @Cacheable(key = "T(String).valueOf(#id).concat('-').concat(#code).concat('-').concat('list')")
    public List<ErrorcodeLocal> list(Long id, String code, int offset, int limit) {
        if (offset < 0) {
            offset = 0;
        }

        if (limit < 0) {
            limit = Page.limit;
        }
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return errorcodeLocalDAO.list(param, new RowBounds(offset, limit));
    }

    @Override
    public int count(Long id, String code) {
        Map<String, Object> param = new HashMap<>();
        param.put("id", id);
        param.put("code", code);
        return errorcodeLocalDAO.count(param);
    }

    /**
     * 修改错误码
     *
     * @param errorcodeLocal
     */
    @Override
//    @CacheEvict(allEntries = true)
    public void update(ErrorcodeLocal errorcodeLocal) {
        errorcodeLocalDAO.update(errorcodeLocal);
    }

    /**
     * 根据errorCode和language查询错误码信息
     *
     * @param errorCode 错误码
     * @param language  语言
     * @return List<ErrorcodeLocal>
     */
    @Override
    public List<ErrorcodeLocal> listByErrorCode(String errorCode, String language) {
        return errorcodeLocalDAO.listByErrorCode(errorCode, language);
    }

}
